package at.socialconference.web.client.ui;

import java.util.List;

import at.socialconference.inter.model.User;
import at.socialconference.web.client.SCwebService;
import at.socialconference.web.client.util.AsyncCallbackGetCountries;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class FriendsSearch extends Composite implements ChangeHandler, KeyUpHandler {

	private static class AsyncCallbackFriendsSearch implements AsyncCallback<List<User>> {
		PeopleTable peopleTable;

		public AsyncCallbackFriendsSearch(PeopleTable peopleTable) {
			this.peopleTable = peopleTable;
		}

		@Override
		public void onFailure(Throwable caught) {
			Window.alert("Internal server error");

		}

		@Override
		public void onSuccess(List<User> result) {
			peopleTable.setData(result);
		}

	}

	private PeopleTable peopleTable;
	private TextBox txtBoxFirstName;
	private TextBox txtBoxLastName;
	private ListBox country;

	public FriendsSearch() {
		VerticalPanel searchPanel = new VerticalPanel();
		initWidget(searchPanel);

		Label lblFirstName = new Label("First Name:");
		searchPanel.add(lblFirstName);

		txtBoxFirstName = new TextBox();
		txtBoxFirstName.addKeyUpHandler(this);

		searchPanel.add(txtBoxFirstName);

		Label lblLastName = new Label("Last Name:");
		searchPanel.add(lblLastName);

		txtBoxLastName = new TextBox();
		txtBoxLastName.addKeyUpHandler(this);
		searchPanel.add(txtBoxLastName);

		Label lblCountry = new Label("Country:");
		searchPanel.add(lblCountry);

		country = new ListBox();
		country.addChangeHandler(this);
		searchPanel.add(country);
		country.setVisibleItemCount(1);
		country.addItem("nothing selected", "0");
		SCwebService.Util.getInstance().getCountries(new AsyncCallbackGetCountries(country));

		Label lblEmpty = new Label("");
		searchPanel.add(lblEmpty);

		peopleTable = new PeopleTable();
		searchPanel.add(peopleTable);
		searchPanel.setCellHorizontalAlignment(peopleTable, HasHorizontalAlignment.ALIGN_CENTER);
	}

	private void search() {
		SCwebService.Util.getInstance().searchUser(txtBoxFirstName.getText(), txtBoxLastName.getText(),
				Integer.parseInt(country.getValue(country.getSelectedIndex())), new AsyncCallbackFriendsSearch(peopleTable));
	}

	@Override
	public void onChange(ChangeEvent event) {
		search();
	}

	@Override
	public void onKeyUp(KeyUpEvent event) {
		search();
	}
}
